##########################################################################################
# fig2: Calculation of adjusted macropartisanship in the US according to the three steps #
##########################################################################################
library(ggplot2)
library(tidyverse)
library(zoo)
library(gridExtra)
library(psych)
library(cowplot)
library(lubridate)





###-----usa
usa<-read.csv("USA_FINAL.csv")
attach(usa)
usa$perdemocrat<-democrat/(democrat+republican)

#basic fomulation
usa$macropartisanship_1<-(democrat/(democrat+republican))*(enpp_np/2)*(((democrat+republican)/independent)*(1/enpp_np^2))
describe(usa$macropartisanship_1)

#weighting process
usa$macrop_var<-var(usa$macropartisanship_1)
usa$macroper_var<-var(usa$perdemocrat)

usa$macropartisanship_USA<-(usa$macropartisanship_1/usa$macrop_var+usa$perdemocrat/usa$macroper_var)/(1/usa$macrop_var+1/usa$macroper_var)


#plot the simple macropartisanship and the modified
df<-data.frame(usa$yearMon,usa$perdemocrat,usa$macropartisanship_USA) 
names(df)[2]<-"Major party share(conventional macropartisanship)"
names(df)[3]<-"Newly defined Macropartisanship"
df2<-df %>% 
  gather(key="Indices", value="value", -usa.yearMon)

#plot and save 

usa_fig<-ggplot(df2, aes(x = as.yearmon(as.Date(df2$usa.yearMon)), y = value)) + 
  geom_line(aes(color = Indices), size = 1) +
  scale_color_manual(values = c("grey", "black")) +
  theme_minimal()+
  xlab("Year")+
  theme(legend.position = 'none')+
  ggtitle("USA (Mean ENPP:1.94)")


ggsave(file = "usa_fig.pdf", plot = usa_fig)